# -*- coding:utf-8 -*-
# @Time : 21-9-1 上午10:02 
# @Author : zdy
# @File : UIDevice.py
# desc:
import threading
from time import sleep

from UIONH.DeviceONH import Ui_Device
from Class.Devices import *
import pyqtgraph as pg
from Class.GraphBase import GraphBase
from importQT import *
from Class.VoltSignal import dataBase

class UIDevice(QDialog, Ui_Device):
    def __init__(self):
        super(UIDevice, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("调试设备")
        self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint)
        # self.setFixedSize(self.width(), self.height())
        self.applyResource()
        device.baseData.disableTest()  # 基线停止调零
        self.init = True
        self.abort = True #True 终止PID功率调节线程
        self.backgroundOpen = "#00FFFF"
        self.backgroundClose = "#F0F8FF"
        self.colors = ["background-color: rgb" + str(color1), "background-color: rgb" + str(color2),
                       "background-color: rgb" + str(color3), "background-color: rgb" + str(color4)]
        self.refreshDO()
        # <editor-fold desc="AD">
        device.sigBaseLineUpdate.connect(self.baseline_update)
        self.initGraph()
        btn = [self.btnAD0, self.btnAD1, self.btnAD2, self.btnAD3]
        for i in range(dataBase.maxChannel):
            btn[i].clicked.connect(self.btnAD_clicked)
            if device.config.channels[i].enable:
                btn[i].setStyleSheet(self.colors[i])
                self.base[i].show()
            else:
                self.base[i].hide()

        # </editor-fold>
        self.btnOut.clicked.connect(self.btnOut_clicked)
        self.btnMFC.clicked.connect(self.btnMFC_clicked)
        self.btnReset.clicked.connect(self.btnReset_clicked)
        self.btnZero.clicked.connect(self.btnZero_clicked)
        self.chkControl.stateChanged.connect(self.chkControl_stateChanged)
        self.chkZero.stateChanged.connect(self.chkZero_stateChanged)
        self.gbDO.setEnabled(False)
        self.gbDA.setEnabled(False)
        self.baselineNo = 1     #1:原始信号；2：调零后信号
        self.dSpinBoxMFC.setValue(device.systemconfig.daq.DAFLowSet)

    def initGraph(self):
        self.baseline_list = [list(), list(), list(), list()]
        self.baseline_t = list()
        self.baseline_count = 0
        self.graphBase = GraphBase(self,title='基线')
        self.graph = self.graphBase.graphwiget
        self.graph.setLabel("left", "U/v")
        self.graph.setLabel("bottom", "T/s")
        self.base = [self.graph.plot(pen=pg.mkPen(color=(128, 0, 0), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(30, 144, 255), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(255, 0, 255), width=2)),
                     self.graph.plot(pen=pg.mkPen(color=(255, 0, 0), width=2))]
        self.verticalLayout.insertWidget(1, self.graph)

        action2 = QAction("清空数据", self.graph)
        action2.triggered.connect(self.graph_clear)
        self.graph.addAction(action2)

    def refreshDO(self):
        """刷新DO状态"""
        # <editor-fold desc="DO">
        btn = [self.btn0, self.btn1, self.btn2, self.btn3, self.btn4, self.btn5, self.btn6, self.btn7, self.btn8,
               self.btn9, self.btn10, self.btn11, self.btn12, self.btn13, self.btn14, self.btn15, self.btn16]
        nums = len(btn)
        for i in range(nums):
            if self.init:   #防止绑定多次
                btn[i].clicked.connect(self.btnDO_clicked)
            state = device.cardGetDO(i)
            if state:
                btn[i].setStyleSheet("background-color:" + self.backgroundOpen)
            else:
                btn[i].setStyleSheet("background-color:" + self.backgroundClose)
        self.init = False
        # </editor-fold>

    def graph_clear(self):
        self.baseline_count = 0
        self.baseline_t.clear()
        for i in range(dataBase.maxChannel):
            self.baseline_list[i].clear()

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def btnMFC_clicked(self):
        v = self.dSpinBoxMFC.value()
        device.controlMFC(False, v, True)

    def btnOut_clicked(self):
        """可控硅控制"""
        if self.rdbtnVolt.isChecked():
            v = self.dSpinBoxVlot.value()
            if v >0 and (not device.monitor.furnaceStatus):
                QMessageBox.warning(self, "提示", "升炉后才可输出")
                return
            else:
                device.controlSCR(v)
        if self.rdbtnPower.isChecked():
            v = self.dSpinBoxPower.value()
            if v >0 and (not device.monitor.furnaceStatus):
                QMessageBox.warning(self, "提示", "升炉后才可输出")
                return
            else:
                self.abort = False
                t = threading.Thread(target=self.PID, kwargs ={"v": v, "type":0})
                # 后台线程
                t.setDaemon(True)
                t.start()
                self.btnOut.setEnabled(False)
        if self.rdbtnI.isChecked():
            v = self.dSpinBoxI.value()
            if v >0 and (not device.monitor.furnaceStatus):
                QMessageBox.warning(self, "提示", "升炉后才可输出")
                return
            else:
                self.abort = False
                t = threading.Thread(target=self.PID, kwargs ={"v": v, "type":1})
                # 后台线程
                t.setDaemon(True)
                t.start()
                self.btnOut.setEnabled(False)

    def PID(self, v, type:int):
        while not self.abort:
            device.PID(v,type)
            sleep(0.5)

    def btnReset_clicked(self):
        if not self.abort:
            self.abort = True
            sleep(1)
        device.controlSCR(0)
        self.btnOut.setEnabled(True)

    def baseline_update(self, data):
        """基线信号更新"""
        self.baseline_count += 1
        self.baseline_t.append(self.baseline_count / device.systemconfig.daq.freq)
        for i in range(dataBase.maxChannel):
            self.baseline_list[i].append(data[self.baselineNo][i])
            self.base[i].setData(self.baseline_t, self.baseline_list[i])
        if device.monitor.furnaceStatus:
            self.DIFurnaceState.setStyleSheet("background-color:" + self.backgroundOpen)
        else:
            self.DIFurnaceState.setStyleSheet("background-color:" + self.backgroundClose)

    def btnDO_clicked(self):
        """DO阀的控制：根据上次的DO输出，执行相反动作，并更新按钮按钮背景"""
        btn = self.sender()
        name = btn.objectName()
        index = int(name[3:])
        # btn.setStyleSheet("background-color:rgb(255, 128, 64);")
        color = btn.palette().color(QPalette.Background)
        if color == QColor(self.backgroundOpen):
            device.cardCloseValve(index)
            if device.cardOutput():
                btn.setStyleSheet("background-color:" + self.backgroundClose)
        else:
            device.cardOpenValve(index)
            if device.cardOutput():
                btn.setStyleSheet("background-color:" + self.backgroundOpen)

    def btnAD_clicked(self):
        """基线显示隐藏设置"""
        btn = self.sender()
        name = btn.objectName()
        index = int(name[5:])
        color = btn.palette().color(QPalette.Background)
        if color == QColor(self.backgroundClose):
            self.base[index].show()
            btn.setStyleSheet(self.colors[index])
        else:
            self.base[index].hide()
            btn.setStyleSheet("background-color:" + self.backgroundClose)

    def chkControl_stateChanged(self, checkState):
        if checkState == Qt.Checked:
            self.gbDO.setEnabled(True)
            self.gbDA.setEnabled(True)
        else:
            self.gbDO.setEnabled(False)
            self.gbDA.setEnabled(False)
            if device.card.isLinked:
                device.reset()
        self.refreshDO()

    def chkZero_stateChanged(self, checkState):
        if checkState == Qt.Checked:
            device.bRefreshVimax = False
            self.baselineNo = 2
        else:
            device.bRefreshVimax = True
            self.baselineNo = 1

    def btnZero_clicked(self):
        v = self.dSpinBoxZero.value()
        device.controlZero(2, v)

    def closeEvent(self, event):
        device.baseData.enableTest()
        device.sigBaseLineUpdate.disconnect(self.baseline_update)
        if device.card.isLinked and self.chkControl.checkState() == Qt.Checked:
            device.reset()
